<template>
  <el-container>
    <!-- 侧边栏 -->
    <el-aside class="home-aside" width="250px">
      <!-- logo -->
      <div class="home-logo-div" v-if="!isOwner">
        <router-link to="/customer/home">
          <el-image
            class="home-logo"
            src="../src/assets/logo_trans.png"
            fit="contain"
          ></el-image
        ></router-link>
      </div>
      <div class="home-logo-div" v-if="isOwner">
        <router-link to="/owner/home">
          <el-image
            class="home-logo"
            src="../src/assets/logo_trans.png"
            fit="contain"
          ></el-image
        ></router-link>
      </div>
      <!-- 折叠icon -->
      <el-icon
        class="toggle-button"
        v-model="isCollapse"
        @click="toggleCollapse"
        size="20px"
      >
        <Fold v-if="!isCollapse" />
        <Expand v-if="isCollapse" />
      </el-icon>
      <!-- 侧边栏菜单 -->
      <el-menu
        class="home-menu-vertical"
        :collapse="isCollapse"
        :default-active="$route.path"
        router
        active-text-color="#E3A566"
        v-if="!isOwner"
      >
        <el-menu-item index="/customer/food">
          <el-icon><Search /></el-icon>
          <span slot="title">菜品列表</span>
        </el-menu-item>
        <el-menu-item index="/customer/recommend">
          <el-icon><MagicStick /></el-icon>
          <span slot="title">猜你想吃</span>
        </el-menu-item>
        <el-menu-item index="/customer/order">
          <el-icon><Wallet /></el-icon>
          <span slot="title">我的订单</span>
        </el-menu-item>
        <el-menu-item index="/customer/account">
          <el-icon><User /></el-icon>
          <span slot="title">我的账号</span>
        </el-menu-item>
      </el-menu>
      <el-menu
        class="home-menu-vertical"
        :collapse="isCollapse"
        :default-active="$route.path"
        router
        v-if="isOwner"
      >
        <el-menu-item index="/owner/food">
          <el-icon>
            <Edit />
          </el-icon>
          <span slot="title">菜品管理</span>
        </el-menu-item>
        <el-menu-item index="/owner/order">
          <el-icon>
            <Bell />
          </el-icon>
          <span slot="title">订单管理</span>
        </el-menu-item>
        <el-menu-item index="/owner/account">
          <el-icon>
            <User />
          </el-icon>
          <span slot="title">我的账号</span>
        </el-menu-item>
      </el-menu>
      <el-image src="../src/assets/plate.png" class="plate-div"></el-image>
    </el-aside>

    <el-container>
      <!-- 头部 -->
      <el-header class="food-header" height="40px">
        <div class="ball"></div>
        <div class="food-line"></div>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/customer/home' }" v-if="!isOwner">
            主页
          </el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/owner/home' }" v-if="isOwner">
            主页
          </el-breadcrumb-item>
          <el-breadcrumb-item>我的账号</el-breadcrumb-item>
        </el-breadcrumb>
      </el-header>

      <!-- 主体 -->
      <el-main class="home-main">
        <el-scrollbar height="590px">
          <!-- 账号卡片 -->
          <el-card class="account-card">
            <!-- 头像 -->
            <el-avatar class="" :src="userEntity.avatar" fit="cover" :size="60">
            </el-avatar>
            <!-- 右侧信息 -->
            <div>
              <el-divider content-position="center">账号信息</el-divider>
              <el-descriptions :column="2" class="orderdetail-des">
                <el-descriptions-item label="用户名">{{
                  userEntity.username
                }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div v-if="!isOwner">
              <el-divider content-position="center">个人信息</el-divider>
              <el-descriptions :column="2" class="orderdetail-des">
                <el-descriptions-item label="故乡">{{
                  userEntity.nativeplace
                }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{
                  userEntity.gender
                }}</el-descriptions-item
                ><el-descriptions-item label="生日">{{
                  userEntity.birthday
                }}</el-descriptions-item></el-descriptions
              >
              <el-divider content-position="center">喜好设置</el-divider>
              <el-descriptions :column="2" class="orderdetail-des">
                <el-descriptions-item label="辣">
                  <el-rate
                    v-model="userFlavor.spicy"
                    :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
                    show-text
                    void-icon="ChatRound"
                    :colors="['#409eff', '#67c23a', '#FF9900']"
                    disabled
                /></el-descriptions-item>
                <el-descriptions-item label="甜">
                  <el-rate
                    v-model="userFlavor.sweet"
                    :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
                    show-text
                    void-icon="ChatRound"
                    :colors="['#409eff', '#67c23a', '#FF9900']"
                    disabled
                /></el-descriptions-item>
                <el-descriptions-item label="咸">
                  <el-rate
                    v-model="userFlavor.salted"
                    :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
                    show-text
                    void-icon="ChatRound"
                    :colors="['#409eff', '#67c23a', '#FF9900']"
                    disabled /></el-descriptions-item
                ><el-descriptions-item label="酸">
                  <el-rate
                    v-model="userFlavor.acid"
                    :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
                    show-text
                    void-icon="ChatRound"
                    :colors="['#409eff', '#67c23a', '#FF9900']"
                    disabled /></el-descriptions-item
                ><el-descriptions-item label="重口">
                  <el-rate
                    v-model="userFlavor.heavyTaste"
                    :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
                    show-text
                    void-icon="ChatRound"
                    :colors="['#409eff', '#67c23a', '#FF9900']"
                    disabled /></el-descriptions-item
                ><el-descriptions-item label="热">
                  <el-rate
                    v-model="userFlavor.hotLevel"
                    :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
                    show-text
                    void-icon="ChatRound"
                    :colors="['#409eff', '#67c23a', '#FF9900']"
                    disabled /></el-descriptions-item
              ></el-descriptions>
            </div>
            <el-button
              class="account-button"
              round
              color="#E3A566"
              @click="openModifyDialog"
              >修改信息</el-button
            ><el-button class="account-button" color="grey" round @click="clickLogOutBtn"
              >退出登录</el-button
            ></el-card
          ></el-scrollbar
        >
      </el-main>
      <!-- 回到顶部 -->
      <el-backtop :right="80" :bottom="100" />
    </el-container>
  </el-container>
  <!-- 修改信息 -->
  <el-dialog v-model="dialogFormVisible" title="修改信息" class="account-dialog">
    <el-form
      :model="registerForm"
      :rules="registerRules"
      ref="registerRuleForm"
      :inline="true"
    >
      <el-form-item label="头&nbsp像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/photo/upload/avatar"
          :show-file-list="false"
        >
          <img v-if="step1Form.avatar" :src="step1Form.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-divider content-position="center">账号信息</el-divider>
      <el-form-item label="账&nbsp号" prop="username">
        <!-- 账号输入框 -->
        <el-input v-model="step1Form.username" input-width="50px"></el-input>
      </el-form-item>
      <el-form-item label="密&nbsp码" prop="password">
        <!-- 密码输入框 -->
        <el-input v-model="step1Form.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="step1Form.confirmPassword" show-password></el-input>
      </el-form-item>
    </el-form>
    <div v-if="!isOwner">
      <el-divider content-position="center">个人信息</el-divider>
      <el-form
        :model="step1Form"
        :rules="step1Rules"
        ref="step1RuleForm"
        size="small"
        :inline="true"
      >
        <el-form-item label="性&nbsp别" prop="sex">
          <el-radio-group v-model="step1Form.gender">
            <el-radio label="male"
              ><el-icon><Male /></el-icon>男</el-radio
            >
            <el-radio label="female"
              ><el-icon><Female /></el-icon>女</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="家&nbsp乡" prop="hometown">
          <el-cascader
            size="small"
            :options="hometownOptions"
            v-model="selectedOptions"
            @change="handleChange"
            placeholder=" "
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="生&nbsp日" prop="birthday">
          <el-date-picker v-model="step1Form.birthday" type="date" placeholder="" />
        </el-form-item>
      </el-form>

      <el-divider content-position="center">口味设置</el-divider>
      <el-form
        :model="step2Form"
        ref="step2RuleForm"
        size="small"
        :inline="true"
        label-position="right"
      >
        <el-form-item label="辣" prop="spicy">
          <el-rate
            v-model="step2Form.spicy"
            :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
            show-text
            void-icon="ChatRound"
            :colors="['#409eff', '#67c23a', '#FF9900']"
          />
        </el-form-item>
        <el-form-item label="甜" prop="sweet">
          <el-rate
            v-model="step2Form.sweet"
            :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
            show-text
            void-icon="ChatRound"
            :colors="['#409eff', '#67c23a', '#FF9900']"
          />
        </el-form-item>
        <el-form-item label="咸" prop="salted">
          <el-rate
            v-model="step2Form.salted"
            :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
            show-text
            void-icon="ChatRound"
            :colors="['#409eff', '#67c23a', '#FF9900']"
          />
        </el-form-item>
        <el-form-item label="酸" prop="acid">
          <el-rate
            v-model="step2Form.acid"
            :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
            show-text
            void-icon="ChatRound"
            :colors="['#409eff', '#67c23a', '#FF9900']"
          />
        </el-form-item>
        <el-form-item label="重口" prop="heavyTaste">
          <el-rate
            v-model="step2Form.heavyTaste"
            :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
            show-text
            void-icon="ChatRound"
            :colors="['#409eff', '#67c23a', '#FF9900']"
          />
        </el-form-item>
        <el-form-item label="热" prop="hotLevel">
          <el-rate
            v-model="step2Form.hotLevel"
            :texts="['很不喜欢', '不太喜欢', '一般', '比较喜欢', '很喜欢']"
            show-text
            void-icon="ChatRound"
            :colors="['#409eff', '#67c23a', '#FF9900']"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button class="loginBtn" round color="#E3A566" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { mapState } from "vuex";
import { provinceAndCityData, codeToText } from "element-china-area-data";
import { ElMessageBox, ElMessage } from "element-plus";
export default {
  data() {
    return {
      isCollapse: false, //是否折叠侧边栏
      hometownOptions: provinceAndCityData,
      userEntity: {},
      userFlavor: {},
      dialogFormVisible: false,
      registerForm: {
        username: "",
        password: "",
        confirmPassword: "",
      },
      registerRules: {
        username: [
          { message: "请输入账号", trigger: "blur" },
          { min: 6, max: 12, message: "长度在 6 到 12 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 12, message: "长度在 6 到 12 个字符", trigger: "blur" },
          {
            pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,12}$/,
            message: "密码必须包含至少一个字母和一个数字",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" },
        ],
      },
      step1Form: {},
      step1Rules: {
        sex: [{ message: "请选择您的性别", trigger: "change" }],
        hometown: [{ message: "请选择您的家乡", trigger: "change" }],
        birthday: [{ type: "date", message: "请选择您的生日", trigger: "change" }],
      },
      step2Form: {
        userID: "",
        spicy: "",
        sweet: "",
        salted: "",
        acid: "",
        heavyTaste: "",
        hotLevel: "",
      },
      selectedOptions: [],
      isOwner: false,
    };
  },
  created() {
    //获取账户的基本信息
    this.userEntity = JSON.parse(this.$store.state.account);
    this.step1Form = JSON.parse(this.$store.state.account);
    this.step1Form.avatar = "http://localhost:8080" + this.step1Form.avatar;
    this.userEntity.avatar = "http://localhost:8080" + this.userEntity.avatar;
    this.isOwner = JSON.parse(this.$store.state.account).id === 1 ? true : false;
    if (!this.isOwner) {
      this.step2Form.userID = this.userEntity.id;
      this.setUserInfo(this.userEntity);

      // 获取账户的口味偏好信息
      let url = "/userflavor/id/" + this.userEntity.id;
      let _this = this;
      this.$http.get(url).then(function (response) {
        _this.userFlavor = response.data;
        if (_this.userFlavor != "") {
          _this.step2Form = response.data;
        }
      });
    }
  },
  methods: {
    setUserInfo(userEntity) {
      userEntity.gender = "male" ? "男" : "女";
      if (userEntity.nativeplace === null) {
        userEntity.nativeplace = "未填写";
      }
      userEntity.birthday = userEntity.birthday.substring(0, 10);
    },
    handleChange() {
      //获取到更改后的籍贯信息
      this.step1Form.nativeplace = "";
      for (let i = 0; i < this.selectedOptions.length; i++) {
        this.step1Form.nativeplace += codeToText[this.selectedOptions[i]];
      }
      console.log(this.step1Form.nativeplace); //打印区域码所对应的属性值即中文地址
    },
    // 切换侧边栏的折叠与展开
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },
    openModifyDialog() {
      this.dialogFormVisible = true;
    },
    // 账号头像
    handleAvatarSuccess(response, uploadFile) {
      this.step1Form.avatar = "http://localhost:8080" + response;
    },
    save() {
      let _this = this;
      this.$refs["registerRuleForm"].validate((valid) => {
        //如果数据格式不符合要求,直接返回
        if (!valid) {
          _this.$message({
            message: "请输入正确格式的数据！",
            type: "error",
          });
          return;
        }
        // 修改个人基本信息
        let url = "/users";

        console.log(this.step1Form);
        let updateFrom = JSON.parse(JSON.stringify(this.step1Form));
        updateFrom.avatar = updateFrom.avatar.replace("http://localhost:8080", "");
        this.$http
          .put(url, updateFrom)
          .then(function (response) {
            // 重新设置个人账户的信息并保存在状态中
            _this.userEntity = updateFrom;
            _this.$store.commit("setAccount", _this.userEntity);
            _this.userEntity.avatar = "http://localhost:8080" + _this.userEntity.avatar;
            _this.userEntity.gender = "male" ? "男" : "女";
            let tmpThis = _this;
            url = "/userflavor";
            if (_this.userFlavor != "") {
              //口味信息不为空则修改口味信息
              _this.$http.put(url, _this.step2Form).then(function (response) {
                tmpThis.$message({
                  message: "信息修改成功！",
                  type: "success",
                });
                //修改成功后重新设置信息
                tmpThis.userFlavor = tmpThis.step2Form;
              });
              return;
            }
            //口味信息为空则新增口味信息
            _this.$http.post(url, _this.step2Form).then(function (response) {
              tmpThis.$message({
                message: "信息修改成功！",
                type: "success",
              });
              //新增成功后重新设置信息
              tmpThis.userFlavor = tmpThis.step2Form;
            });
          }) //捕获到错误信息
          .catch(function (error) {
            _this.$message({
              message: "信息修改失败！",
              type: "error",
            });
          });
        this.dialogFormVisible = false;
      });
    },
    clickLogOutBtn() {
      ElMessageBox.confirm("", "确定要退出登录吗", {
        confirmButtonText: "确认退出",
        cancelButtonText: "我再想想",
      })
        .then(() => {
          var _this = this;
          _this.$store.commit("logout");
          // 清空状态中的购物车
          _this.$store.dispatch("updateFoodInCart", []);
          _this.$router.push({
            path: "/",
          });
          // 确认按钮被点击时执行的操作
          ElMessage({
            type: "success",
            message: "退出登录",
          });
        })
        .catch(() => {
          // 取消按钮被点击时执行的操作
          ElMessage({
            type: "info",
            message: "取消",
          });
        });
    },
  },
};
</script>

<style>
.account-card {
  padding: 20px;
  width: 800px;
  margin: 0 auto;
  border-radius: 20px;
}
.account-button {
  margin: 20px 0px 0px;
  font-size: 18px !important;
  font-family: sanji !important;
  color: white !important;
}
/* 对话框的叉 */
.el-dialog__headerbtn:focus .el-dialog__close,
.el-dialog__headerbtn:hover .el-dialog__close {
  color: #e3a566 !important;
}
.account-dialog {
  padding: 0px 20px 0px;
}
</style>
